<template>
	<mips-editor
		v-if="value"
		:program-info.sync="value"
		:deviceList.sync="deviceList"
		:currentProgramInfo.sync="currentProgramInfo"
		:schedulingList.sync="schedulingList"
		:openAuditSwitch.sync="openAuditSwitch"
		:group-options.sync="groupOptions"
		:material-group-options.sync="materialGroupOptions"
		:template-group-options.sync="templateGroupOptions"
		:img-options.sync="imgOptions"
		:video-options.sync="videoOptions"
		:template-options.sync="templateOptions"
		:music-options.sync="musicOptions"
		:dataset-options="datasetOptions"
		:pdf-options.sync="pdfOptions"
		:district-list="districtList"
		@img-current-change="handleImageCurrentChange"
		@img-size-change="handleImageSizeChange"
		@video-current-change="handleVideoCurrentChange"
		@video-size-change="handleVideoSizeChange"
		@template-current-change="handleTemplateCurrentChange"
		@template-size-change="handleTemplateSizeChange"
		@music-current-change="handleMusicCurrentChange"
		@music-size-change="handleMusicSizeChange"
		@dataset-current-change="handleDatasetCurrentChange"
		@dataset-size-change="handleDatasetSizeChange"
		@pdf-current-change="handlePdfCurrentChange"
		@pdf-size-change="handlePdfSizeChange"
		@delete-component="handleDeleteComponent"
		@back="handleBack"
		@save="handleSave"
		@getDevice="getDevice"
		@getGroupNameTree="getGroupNameTree"
		@createChannel="createChannel"
		@getImageList="getImageList"
		@getVideoList="getVideoList"
		@getFileList="getFileList"
		@getAudioList="getAudioList"
		@getTemplateList="getTemplateList"
		@handleClickSaveGroup="handleClickSaveGroup"
		@deleteGroup="deleteGroup"
		@uploadFiles="uploadFiles"
		@submitForm="submitForm"
	/>
</template>

<script>
import { uploadCover } from '@/api/ips/command'
import { addProgram, editProgram, listProgram } from '@/api/ips/program'
import { getV, remove } from '@/utils/storage-util'
import {
	listMaterial as il,
	listMaterial as vl,
	listMaterial as fl,
	uploadMaterial,
	addMaterial,
	editMaterial,
} from '@/api/ips/material'
import { getAccessToken } from '@/data/user'
import { listDataset } from '@/api/system/dataset'
import { call, equals as deepEquals } from 'ramda'
import {
	groupTree,
	delGroup,
	addGroup,
	editGroup,
	whetherMaterial,
} from '@/api/ips/group'
import { listDeviceScheduling } from '@/api/ips/device'
import { listConfig } from '@/api/system/config'
import {
	addScheduling,
	editReleaseScheduling,
	listScheduling,
} from '@/api/ips/scheduling'
import Store from '@/store/index'

export default {
	name: 'Editor',
	data() {
		return {
			value: undefined,
			imgOptions: {
				imageList: [],
				current: 1,
				size: 6,
				total: 0,
				sizes: [6, 12, 24, 60, 120],
			},
			groupOptions: [],
			materialGroupOptions: [],
			templateGroupOptions: [],
			deviceList: [],
			videoOptions: {
				videoList: [],
				current: 1,
				size: 6,
				total: 0,
				sizes: [6, 12, 24, 60, 120],
			},
			templateOptions: {
				templateList: [],
				current: 1,
				size: 6,
				total: 81,
				sizes: [6, 12, 24, 60, 120],
			},
			musicOptions: {
				musicList: [],
				current: 1,
				size: 10,
				total: 0,
				sizes: [10, 20, 50, 100],
			},
			datasetOptions: {
				datasetList: [],
				current: 1,
				size: 10,
				total: 0,
				sizes: [10, 20, 50, 100],
			},
			pdfOptions: {
				pdfList: [],
				current: 1,
				size: 6,
				total: 0,
				sizes: [6, 12, 24, 60, 120],
			},
			districtUrl:
				'/amap/config/district?subdistrict=3&extensions=base&key=78b8ade233d6ccc9f6411cd49ebcbc0c',
			districtList: [],
			form: {},
			deviceForm: {
				// 表单参数
				id: undefined,
				deviceId: [],
				devices: [],
				status: 2,
			},
			queryParams: {},
			// 设备查询参数
			queryParamsDevice: {
				// current: 1,
				// size: 999999,
				// status: 1,
				id: undefined,
				fullPathId: undefined,
			},
			currentProgramInfo: {},
			openAuditSwitch: true,
			schedulingList: [],
			staticPort: '',
		}
	},
	created() {
		this.queryParams = this.$route.params //接受参数
		this.currentProgramInfo = this.queryParams.program
			? [this.queryParams.program]
			: []
		// 获取后端ip
		this.staticPort = Store.state.user.staticPort
		// axios.get(this.districtUrl)
		//   .then(res => {
		//     // console.log('object', res.districts[0].districts)
		//     this.districtList = res.districts[0].districts
		//   })
		//   .catch(_ => {
		//   })
		// queryRegion().then(res => {
		//   this.districtList = res.data
		// })
		this.getTemplateList()
		this.getImageList()
		this.getVideoList()
		this.getAudioList()
		this.getFileList()
		this.getDatasetList()
		this.getDevice()
		this.getGroupNameTree()
		this.getMaterialGroupTree()
		this.getTemplateGroupTree()
		this.getList()
		this.form = JSON.parse(getV('PROGRAM_INFO'))
		if (!this.form) {
			return
		}
		if (!this.form.id) {
			// 新增节目
			let width, height
			if (this.form.resolution !== '自定义') {
				;[width, height] = this.form.resolution.split('*')
			} else {
				width = this.form.customWidth
				height = this.form.customHeight
			}
			width = Number.parseInt(width)
			height = Number.parseInt(height)
			this.value = {
				id: null,
				IS_TEMPLATE: getV('PREVIOUS_ROUTE') === 'template' ? 1 : 0,
				name: this.form.name,
				groupId: this.form.groupId,
				groupName: this.form.groupName,
				width: width,
				height: height,
				scale: 1.0,
				remarks: '',
				bgColor: '',
				bgImg: '',
				isTemplate:
					this.form.isTemplate !== null && this.form.isTemplate !== undefined
						? this.form.isTemplate
						: 1,
				pages: [
					{
						id: 1,
						title: '场景1',
						duration: null,
						componentList: [],
						imgId: null,
						bgImg: '',
						bgColor: '#fff',
						customScript: '',
						datasetId: '',
						datasetName: '',
						datasetFields: '',
						datasetParams: '',
						interval: 10,
					},
				],
			}
			console.log('debug val=', this.value)
		} else {
			// 编辑节目
			const form1 = JSON.parse(this.form.layout)
			form1.width = Number.parseInt(form1.width)
			form1.height = Number.parseInt(form1.height)
			this.value = form1
		}
	},
	beforeDestroy() {
		remove('PROGRAM_INFO')
		remove('PREVIOUS_ROUTE')
	},
	methods: {
		// 保存素材
		submitForm(formList, currentId, currentName, type, isConvert) {
			for (let key in formList) {
				formList[key].groupId = currentId
				formList[key].groupName = currentName
				if (isConvert == '1') {
					formList[key].isConvert = isConvert
				}
				if (formList[key].id) {
					editMaterial(formList[key]).then((response) => {
						if (response.code === 0) {
							switch (response.data) {
								case 'image':
									this.msgSuccess(this.$t('addImageSuccess'))
									break
								case 'audio':
									this.msgSuccess(this.$t('addMedioSuccess'))
									break
								case 'medio':
									this.msgSuccess(this.$t('addAudioSuccess'))
									break
								case 'file':
									this.msgSuccess(this.$t('addFileSuccess'))
									break
							}
							switch (type) {
								case 'img':
									this.getImageList(currentId)
									break
								case 'video':
									this.getVideoList(currentId)
									break
								case 'pdf':
									this.getFileList(currentId)
									break
								case 'music':
									this.getAudioList(currentId)
									break
								case 'template':
									this.getTemplateList(currentId)
									break
							}
						} else {
							this.msgError(response.msg)
						}
					})
				} else {
					addMaterial(formList[key]).then((response) => {
						if (response.code === 0) {
							switch (response.data) {
								case 'image':
									this.msgSuccess(this.$t('addImageSuccess'))
									break
								case 'audio':
									this.msgSuccess(this.$t('addMedioSuccess'))
									break
								case 'medio':
									this.msgSuccess(this.$t('addAudioSuccess'))
									break
								case 'file':
									this.msgSuccess(this.$t('addFileSuccess'))
									break
							}
							switch (type) {
								case 'img':
									this.getImageList(currentId)
									break
								case 'video':
									this.getVideoList(currentId)
									break
								case 'pdf':
									this.getFileList(currentId)
									break
								case 'music':
									this.getAudioList(currentId)
									break
								case 'template':
									this.getTemplateList(currentId)
									break
							}
						} else {
							this.msgError(response.msg)
						}
					})
				}
			}
		},
		// 上传素材
		uploadFiles(param) {
			const formData = new FormData()
			formData.append('file', param.file)
			uploadMaterial({
				data: formData,
				headers: { Accept: '*/*', 'Content-Type': 'multipart/form-data' },
			}).then((res) => {
				if (res.code == 0) {
					param.onSuccess(res)
				} else {
					param.onError(err)
				}
			})
		},
		// 获取素材分组列表
		getMaterialGroupTree() {
			groupTree({ groupId: 20 }).then((response) => {
				this.materialGroupOptions = response.data
				this.groupDict = []
				const findChildren = (arr, list) => {
					for (let i = 0; i < arr.length; i++) {
						if (arr[i].id) {
							list.push(arr[i])
						}
						if (arr[i].children && arr[i].children.length) {
							findChildren(arr[i].children, list)
						}
					}
				}
				findChildren(this.materialGroupOptions, this.groupDict)
			})
		},
		// 获取素材模板列表
		getTemplateGroupTree() {
			groupTree({ groupId: 49 }).then((response) => {
				this.templateGroupOptions = response.data
				this.groupDict = []
				const findChildren = (arr, list) => {
					for (let i = 0; i < arr.length; i++) {
						if (arr[i].id) {
							list.push(arr[i])
						}
						if (arr[i].children && arr[i].children.length) {
							findChildren(arr[i].children, list)
						}
					}
				}
				findChildren(this.templateGroupOptions, this.groupDict)
			})
		},
		handleClickSaveGroup(groupObj, callback) {
			const fun = groupObj.id ? editGroup : addGroup
			fun(groupObj)
				.then((_) => {
					this.$message({
						message: this.$t('saveSuccess'),
						type: 'success',
						showClose: true,
					})
					const groupDialogVisible = true
					callback(groupDialogVisible)
					this.getMaterialGroupTree()
					this.getTemplateGroupTree()
				})
				.catch((_) => {})
		},
		// 删除分组
		deleteGroup(data, type) {
			whetherMaterial(data.id).then((response) => {
				if (response.data > 0) {
					this.$message({
						message: '该分组包含素材无法删除',
						type: 'warning',
						showClose: true,
					})
					return false
				}
				this.$confirm(`确认要删除分组："${data.name}"吗?`, '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(function() {
						return delGroup(data.id)
					})
					.then(() => {
						this.getMaterialGroupTree()
						switch (type) {
							case 'img':
								this.getImageList()
								break
							case 'video':
								this.getVideoList()
								break
							case 'pdf':
								this.getFileList()
								break
							case 'music':
								this.getAudioList()
								break
							case 'template':
								this.getTemplateGroupTree()
								this.getTemplateList()
								break
						}
						this.msgSuccess('删除成功')
					})
					.catch(function() {})
			})
		},
		createChannel(basicInfo, currentProgramInfo, deviceForm) {
			if (basicInfo.type === '0') {
				basicInfo.startDate = '1999-12-31'
				basicInfo.stopDate = '2999-12-31'
				basicInfo.startTime = basicInfo.endDateTime[0]
				basicInfo.stopTime = basicInfo.endDateTime[1]
			} else {
				basicInfo.startDate = basicInfo.startDateTime[0]
				basicInfo.stopDate = basicInfo.startDateTime[1]
				basicInfo.startTime = basicInfo.endDateTime[0]
				basicInfo.stopTime = basicInfo.endDateTime[1]
			}
			basicInfo.playWeeks = basicInfo.playWeeks.join(',')
			if (currentProgramInfo.length > 0) {
				const tmp = []
				currentProgramInfo.forEach((element) => {
					tmp.push(element.id)
				})
				basicInfo.programId = tmp.toString()
				basicInfo.programs = JSON.stringify(currentProgramInfo)
			} else {
				basicInfo.programs = ''
				basicInfo.programId = ''
			}
			if (basicInfo.nowDown) {
				basicInfo.isTiming = '0'
				basicInfo.dloadTime = this.parseTime(new Date())
			} else {
				basicInfo.isTiming = '1'
			}
			addScheduling(basicInfo)
				.then((res) => {
					this.$message({
						message: this.$t('saveSuccess'),
						type: 'success',
						showClose: true,
					})
					deviceForm.id = res.data
					// 发布计划
					this.release(deviceForm)
				})
				.catch((_) => {})
		},
		/** 查询参数列表 */
		getList() {
			let queryParams = {
				current: 1,
				size: 1000,
			}
			listConfig(this.addDateRange(queryParams)).then((response) => {
				let configList = response.data
				configList.forEach((config) => {
					if (config.key == 'auditSwitch' && config.value == '2') {
						this.openAuditSwitch = false
					} else if (config.key == 'auditSwitch' && config.value == '1') {
						this.openAuditSwitch = true
					}
				})
			})
		},
		/** 发布按钮 */
		release(deviceForm) {
			let id = deviceForm.id
			let status = 4
			let deviceId = deviceForm.deviceId.toString()
			let devices
			if (deviceForm.devices.length > 0) {
				devices = JSON.stringify(deviceForm.devices)
			} else {
				devices = ''
			}
			if (devices.length === 0) {
				this.$message.warning(this.$t('terminal.atLeastOnce'))
				return
			}
			this.$confirm(this.$t('terminal.enterRelease'), this.$t('tip'), {
				confirmButtonText: this.$t('submitText'),
				cancelButtonText: this.$t('cancelText'),
				type: 'warning',
			})
				.then(function() {
					return editReleaseScheduling({ id, status, deviceId, devices })
				})
				.then(() => {
					this.msgSuccess(this.$t('terminal.releaseSuccess'))
					this.jump()
				})
				.catch(function() {})
		},
		/** 查询分组名称下拉树结构 */
		getGroupNameTree() {
			groupTree({ deptId: this.deptId, groupId: 43 }).then((response) => {
				this.groupOptions = response.data
				this.groupDict = []
				const findChildren = (arr, list) => {
					for (let i = 0; i < arr.length; i++) {
						if (arr[i].id) {
							list.push(arr[i])
						}
						if (arr[i].children && arr[i].children.length) {
							findChildren(arr[i].children, list)
						}
					}
				}
				findChildren(this.groupOptions, this.groupDict)
			})
		},
		// 得到模板列表
		getTemplateList(fullPathId, name) {
			listProgram({
				size: this.templateOptions.size,
				current: this.templateOptions.current,
				isTemplate: 1,
				fullPathId: fullPathId,
				name: name,
			}).then((response) => {
				this.templateOptions.templateList = response.data.map((it) => {
					it.cover = process.env.VUE_APP_BASE_API + it.cover
					return it
				})
				this.templateOptions.total = response.total
			})
		},
		// 得到图片列表
		getImageList(fullPathId, name) {
			il({
				current: this.imgOptions.current,
				size: this.imgOptions.size,
				type: 'image',
				fullPathId: fullPathId,
				name: name,
			}).then((res) => {
				this.imgOptions.imageList = res.data.map((it) => {
					it.url =
						process.env.VUE_APP_BASE_API + (it.decodedUrl || it.originalUrl)
					return it
				})
				this.imgOptions.total = res.total
			})
		},
		// 得到视频列表
		getVideoList(fullPathId, name) {
			vl({
				current: this.videoOptions.current,
				size: this.videoOptions.size,
				type: 'media',
				fullPathId: fullPathId,
				name: name,
			}).then((res) => {
				this.videoOptions.videoList = res.data.map((it) => {
					it.url = `http://` + this.staticPort + it.decodedUrl
					return it
				})
				this.videoOptions.total = res.total
			})
		},
		// 得到音频列表
		getAudioList(fullPathId, name) {
			vl({
				current: this.musicOptions.current,
				size: this.musicOptions.size,
				type: 'audio',
				fullPathId: fullPathId,
				name: name,
			}).then((res) => {
				this.musicOptions.musicList = res.data.map((it) => {
					it.url = process.env.VUE_APP_BASE_API + it.decodedUrl
					return it
				})
				this.musicOptions.total = res.total
			})
		},
		// 得到pdf（文件、文档）列表
		getFileList(fullPathId, name) {
			fl({
				current: this.pdfOptions.current,
				size: this.pdfOptions.size,
				type: 'file',
				fullPathId: fullPathId,
				name: name,
			}).then((res) => {
				this.pdfOptions.pdfList = res.data.map((it) => {
					it.url = process.env.VUE_APP_BASE_API + it.decodedUrl
					return it
				})
				try {
					res.data.forEach((it) => {
						if (!it.addition.split(',')[0].includes('/pro')) {
							it.addition.split(',').forEach((item) => {
								it.addition += process.env.VUE_APP_BASE_API + item
							})
						}
					})
				} catch (error) {}

				// this.pdfOptions.add
				this.pdfOptions.total = res.total
			})
		},

		// 得到数据源列表
		getDatasetList() {
			listDataset({
				size: this.datasetOptions.size,
				current: this.datasetOptions.current,
			}).then((response) => {
				this.datasetOptions.datasetList = response.data
				this.datasetOptions.total = response.total
			})
		},
		/** 查询设备列表 */
		getDevice(fullPathId) {
			this.queryParamsDevice.fullPathId = fullPathId
			this.queryParamsDevice.id = this.deviceForm.id
				? this.deviceForm.id
				: undefined
			listDeviceScheduling(this.queryParamsDevice).then((response) => {
				this.deviceList = []
				response.data.forEach((element) => {
					const temp = {
						id: element.id,
						name: element.name,
						code: element.code,
						groupId: element.groupId,
						groupName: element.groupName,
						resolution: element.resolution,
						platFlag: element.platFlag,
						status: element.status,
						online: element.online,
					}
					this.deviceList.push(temp)
				})
			})
		},
		handleImageCurrentChange: function(val, currentId, filter) {
			console.log('handleImageCurrentChange', val)
			this.imgOptions.current = val
			this.getImageList(currentId, filter)
		},
		handleImageSizeChange: function(val, currentId, filter) {
			console.log('handleImageSizeChange', val)
			this.imgOptions.current = 1
			this.imgOptions.size = val
			this.getImageList(currentId, filter)
		},
		handleVideoCurrentChange: function(val) {
			console.log('handleVideoCurrentChange', val)
			this.videoOptions.current = val
			this.getVideoList()
		},
		handleVideoSizeChange: function(val) {
			console.log('handleVideoSizeChange', val)
			this.videoOptions.current = 1
			this.videoOptions.size = val
			this.getVideoList()
		},
		handleTemplateCurrentChange: function(val) {
			console.log('handleTemplateCurrentChange', val)
			this.templateOptions.current = val
			this.getTemplateList()
		},
		handleTemplateSizeChange: function(val) {
			console.log('handleTemplateSizeChange', val)
			this.templateOptions.current = 1
			this.templateOptions.size = val
			this.getTemplateList()
		},
		handleMusicCurrentChange: function(val) {
			console.log('handleMusicCurrentChange', val)
			this.musicOptions.current = val
			this.getAudioList()
		},
		handleMusicSizeChange: function(val) {
			console.log('handleMusicSizeChange', val)
			this.musicOptions.current = 1
			this.musicOptions.size = val
			this.getAudioList()
		},
		handleDatasetCurrentChange: function(val) {
			console.log('handleTemplateCurrentChange', val)
			this.datasetOptions.current = val
			this.getDatasetList()
		},
		handleDatasetSizeChange: function(val) {
			console.log('handleTemplateSizeChange', val)
			this.datasetOptions.current = 1
			this.datasetOptions.size = val
			this.getDatasetList()
		},
		handlePdfCurrentChange: function(val) {
			console.log('handleTemplateCurrentChange', val)
			this.pdfOptions.current = val
			this.getFileList()
		},
		handlePdfSizeChange: function(val) {
			console.log('handleTemplateSizeChange', val)
			this.pdfOptions.current = 1
			this.pdfOptions.size = val
			this.getFileList()
		},
		handleDeleteComponent({ component, index, confirmCallback }) {
			this.$confirm('确认要删除选择的组件吗?', this.$t('warning'), {
				confirmButtonText: this.$t('submitText'),
				cancelButtonText: this.$t('cancelText'),
				type: 'warning',
			})
				.then((_) => {
					confirmCallback()
				})
				.catch((_) => {})
		},
		handleBack() {
			this.jump()
		},
		/**
		 *
		 * @param data 节目数据
		 * @param blob 节目截图对象
		 * @param callback 回调函数
		 */
		handleSave(data, blob, callback) {
			let jsonLayout =
				this.form.layout === undefined
					? JSON.stringify({ pages: {} })
					: this.form.layout
			console.log(jsonLayout)
			let layout = JSON.parse(jsonLayout)
			let oldPages = layout.pages
			let newPages = data.pages
			for (let i = 0; i < newPages.length; i++) {
				//oldpages旧的场景可能会比新的数据场景小所以要判断是否为空
				let newPage = newPages[i]
				let oldPage = oldPages[i] === undefined ? {} : oldPages[i]
				if (newPage.id === oldPage.id) {
					if (!deepEquals(newPage, oldPage) || !newPage.updateTime) {
						newPage.updateTime = new Date().getTime()
					}
				} else {
					newPage.updateTime = new Date().getTime()
				}
			}

			const saveOrUpdate = (cover) => {
				cover && (this.form.cover = cover)
				// // 重新编排场景编号
				// const temp = data.pages
				// for (let n = 0; n < temp.length; n++) {
				//   temp[n].id = n + 1
				// }
				// data.pages = temp
				this.form.layout = JSON.stringify(data)
				this.form.name = data.name
				this.form.width = data.width
				this.form.height = data.height
				// 提取节目中所有场景数据源的id
				let dataSourceIdsArr = []
				console.log(`<<<<2023年12月29日 16:17:42>>>>`, data.pages)
				for (let i = 0; i < data.pages.length; i++) {
					console.log(`<<<<2023年12月29日 16:17:42>>>>`, data.pages[i])
					if (
						data.pages[i].dataSourceIds &&
						data.pages[i].dataSourceIds.length
					) {
						dataSourceIdsArr.push(...data.pages[i].dataSourceIds)
					}
				}
				console.log(`<<<<2023年12月29日 16:18:14>>>>`, {
					dataSourceIdsArr: dataSourceIdsArr,
				})
				dataSourceIdsArr = Array.from(new Set(dataSourceIdsArr))
				this.form.dataSourceIds = dataSourceIdsArr.join(',')

				console.log(
					'data.dataSourceIds',
					this.form.dataSourceIds,
					data.dataSourceIds
				)
				const result = this.form.id
					? editProgram(this.form)
					: addProgram(this.form)
				result
					.then((res) => {
						callback(true, res.data)
						this.$message.success(this.$t('saveSuccess'))
						this.jump()
					})
					.catch((_) => {
						callback(false)
						this.$message.error('保存失败')
						this.jump()
					})
			}

			const formData = new FormData()
			formData.append('file', blob)
			uploadCover(formData)
				.then((res) => {
					const imgPath = res.data
					saveOrUpdate(imgPath)
				})
				.catch((_) => {})
				.finally(() => {})
		},
		jump() {
			if (getV('PREVIOUS_ROUTE') === 'template') {
				this.$router.replace('/sc/template')
			} else {
				if (this.queryParams.program) {
					delete this.queryParams.program
				}
				this.$router.replace({
					name: 'IpsProgram',
					params: this.queryParams,
				})
				// this.$router.replace('/ipsProgram/index') // 没有这个路径
			}
		},
	},
}
</script>

<style lang="scss" scoped></style>
